package com.wk.filter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * 使用alibaba Sentinel限流
 */
@Component
public class SentinelFilter extends ZuulFilter {


	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		//限流的业务逻辑（使用令牌）
		Entry entry = null;

		//去对应的令牌桶中取令牌，如果获取到，执行业务逻辑，获取不到就会被阻塞
		try {
			//获取令牌桶保护相应的资源
			entry = SphU.entry("name");
			System.out.println("正常请求，继续走后面的过滤器");
			RequestContext.getCurrentContext().setSendZuulResponse(true);
		} catch (BlockException e) {
			e.printStackTrace();
			System.out.println("被阻塞，不走后面的过滤器");
			RequestContext.getCurrentContext().setSendZuulResponse(false);
		}finally {
			if (entry != null) {
				entry.exit();
			}
		}

		return null;
	}
}
